#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time       :   21:36
# Author     : Y4
# Site       : 
# File       : 010 线程的死锁.py
# Software   : PyCharm

'''
解决死锁
    1. 重构
    2. 添加timeout
'''


from threading import Thread,Lock
import time


a = Lock()
b = Lock()

class MyThread(Thread):
    # 重写run方法
    def run(self):
        if a.acquire():     # 如果获得a锁就返回真
            print(self.name + '获得了a锁')
            time.sleep(0.1)
            if b.acquire(timeout=5):
                print(self.name + '获得了b锁,原来还有a锁')
                b.release()
            a.release()

class MyThread1(Thread):
    # 重写run方法
    def run(self):
        if b.acquire():
            print(self.name + '获得了b锁')
            time.sleep(0.1)
            if a.acquire(timeout=5):
                print(self.name + '获得了a锁,原来还有b锁')
                a.release()
            b.release()


if __name__ == '__main__':
    t = MyThread()
    t1 = MyThread1()

    t.start()
    t1.start()


